<?php

namespace App\Http\Controllers\Admin;

use App\Http\Servers\Admin\ImageServer;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Intervention\Image\Facades\Image;

class WaterController extends CommonController
{
    //水印设置
    public function water(Request $request, ImageServer $imageServer)
    {
        if (!extension_loaded('fileinfo')) {
            abort(404);
        }

        if ($request->isMethod('post')) {
            if ($request->has('clearwater')) {
                $update['water'] = '';
                $images = \App\Image::whereIn('tag', array_keys($request->chunk))->lists('water');
                $result = \App\Image::whereIn('tag', array_keys($request->chunk))->update($update);
                if ($result) {
                    foreach ($images as $value) {
                        if (!empty($value) && file_exists('.' . $value)) {
                            unlink('.' . $value);
                        }
                    }
                    $message['message'] = message(true, '清除成功', '所选模块图片水印清除成功!');
                } else {
                    $message['message'] = message(false, '清除失败', '所选模块图片水印清除失败!');
                }
                return back()->with($message);
            } else {
                $this->validate($request, [
                    'water' => 'required|image',
                    'position' => 'required',
                    'chunk' => 'required|array',
                ]);

                $waterId = $imageServer->uploadImage($request->water, 'water', 'water');
                $water = \App\Image::where('id', $waterId)->value('path');
                $images = \App\Image::whereIn('tag', array_keys($request->chunk))->lists('path', 'id');

                foreach ($images as $id => $image) {
                    $watername = pathinfo($image)['dirname'] . '/water-' . pathinfo($image)['basename'];
                    if (file_exists('.' . $image)) {
                        $img = Image::make('.' . $image)->insert('.' . $water, $request->position)->save('.' . $watername);
                        $update['water'] = $watername;
                        \App\Image::where('id', $id)->update($update);
                    }
                }

                $message['message'] = message(true, '设置成功', '水印设置成功!');
                return back()->with($message);
            }
        }

        $data['chunks'] = \App\Chunk::lists('name', 'path')->toArray();

        return view('admin.water.water', $data);
    }
}
